﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace System.IO.Ports
{
    public static class SerialPortExtension
    {
        /// <summary>
        /// 发送十六进制字符串
        /// </summary>
        /// <param name="serialPort"></param>
        /// <param name="hex"></param>
        public static void SendHexString(this SerialPort serialPort, string hex)
        {
            var data = HexToBytes(hex);
            if (!serialPort.IsOpen)
            {
                throw new Exception("串口未打开。");
            }
            serialPort.Write(data, 0, data.Length);
        }

        private static byte[] HexToBytes(string hex, bool autoPaddingLeft = false)
        {
            if (hex.Contains(" "))
            {
                var hexs = hex.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                byte[] data = new byte[hexs.Length];
                for (int i = 0; i < hexs.Length; i++)
                {
                    data[i] = Convert.ToByte(hexs[i], 16);
                }
                return data;
            }
            else
            {
                if (hex.Length % 2 != 0)
                {
                    if (autoPaddingLeft)
                    {
                        hex = "0" + hex;
                    }
                    else
                    {
                        throw new Exception("十六进制字符串字符数必须为2的倍数。");
                    }
                }
                var count = hex.Length / 2;
                byte[] data = new byte[count];
                for (int i = 0; i < count; i++)
                {
                    data[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
                }
                return data;
            }
        }
    }

}
